package com.hgj.blindbox.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hgj.blindbox.entity.BoxItem;
import com.hgj.blindbox.entity.DrawResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class BlindBoxDrawService {
    // Lua脚本路径
    private static final String LUA_SCRIPT_PATH = "scripts/blindbox_draw2.lua";


    private final RedisScript<List> redisScript;

    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public BlindBoxDrawService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.redisScript = loadLuaScript();
    }

    private RedisScript<List> loadLuaScript() {
        DefaultRedisScript<List> script = new DefaultRedisScript<>();
        script.setScriptSource(new ResourceScriptSource(new ClassPathResource(LUA_SCRIPT_PATH)));
        script.setResultType(List.class);
        return script;
    }

    /**
     * 执行抽奖
     * @param userId 用户ID
     * @param boxId 盲盒ID
     * @return 抽奖结果
     */
    public DrawResult draw(String userId, String boxId) {
        // 每日抽奖限制
        int dailyLimit = 5;
        String today = LocalDate.now().toString();

        List<Object> result = redisTemplate.execute(
                redisScript,
                Arrays.asList("user:draw:count:"+userId,
                        "blindbox:weights:"+boxId,
                        "blindbox:stocks:"+boxId,
                        "user:prizes:"+userId),
                boxId, userId, today, String.valueOf(dailyLimit)
        );

        if (result == null || result.size() < 2) {
            return new DrawResult(false, "抽奖失败: 系统错误", null);
        }

        Object status = result.get(0);
        String prizeId = result.get(2).toString();

        if (status.toString().equals("1")) {
            // 获取奖品详情
            BoxItem prize = getPrizeDetails(boxId, prizeId);
            return new DrawResult(true, "恭喜您抽中: " + prize.getName(), prize);
        }

        return new DrawResult(false, "很遗憾未中奖", null);
    }

    /**
     * 获取奖品详情
     * @param boxId 盲盒ID
     * @param prizeId 奖品ID
     * @return 奖品对象
     */
    private BoxItem getPrizeDetails(String boxId, String prizeId) {
        Object itemJson = redisTemplate.opsForHash()
                .get("blindbox:items:" + boxId, prizeId);

        if (itemJson == null) {
            throw new RuntimeException("奖品不存在: " + prizeId);
        }

//        try {
//            BoxItem item = new ObjectMapper().readValue(itemJson.toString(), BoxItem.class);
////            BoxItem item = new BoxItem();
////            item.setId((String) map.get("id"));
////            item.setName((String) map.get("name"));
////            item.setStock(Integer.parseInt((String) map.get("stock")));
////            item.setWeight(Double.parseDouble((String) map.get("weight")));
//            return item;
//        } catch (Exception e) {
//            throw new RuntimeException("解析奖品信息失败", e);
//        }
        return JSONObject.parseObject(itemJson.toString(),BoxItem.class);
    }

}
